const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
const jwtToken = require('./token.js');
const cors = require('cors');

app.use(cors({}))


 const users = [
  { id: 1, username: 'abc', password: '123', email: '123@qq.com' },
  { id: 2, username: 'www', password: '345', email: '345@qq.com' }
];



app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.post('/login', (req, res) => {
  const { username, password } = req.body;
  console.log('Received login request:', { username, password });
  const user = users.find(u => u.username === username);
  if (!user) {
    return res.status(404).json({ status: 'error', message: '账号不存在' });
  }
  if (user.password !== password) {
    return res.status(401).json({ status: 'error', message: '密码错误' });
  }

  const access_token = jwtToken.generateToken(user, '1h');
  const refresh_token = jwtToken.generateToken(user, '7d');


  res.json({ 
    userInfo: {
      id: user.id,
      username: user.username,
      email: user.email
    },
    access_token: access_token,
    refresh_token: refresh_token
  });
})


// 需要 token 验证的路由
app.get('/home', (req, res) => {
  const authorization = req.headers.authorization;
  if (!authorization) {
    return res.status(401).json({ status: 'error', message: '用户未登录' });
  }
  console.log('Received token:', authorization);

  try {
    const token = authorization.split(' ')[1];
    const data = jwtToken.verifyToken(token);
    res.json({ status: 'success', message: '验证通过', data: data })
  } catch (error) {
    return res.status(401).json({ status: error, message: 'token失效，请重新登录' });
  }
})

// 刷新 token
app.get('/refresh', (req, res) => {
  const { token } = req.query;  // 从请求参数中获取 refresh-token

  try {
    const data = jwtToken.verifyToken(token);
    const access_token = jwtToken.generateToken(data, '1h');
    const refresh_token = jwtToken.generateToken(data, '7d');
    res.json({ access_token: access_token, refresh_token: refresh_token });
   
  } catch (error) {
   
  }

})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
})